import methods from "./methods";
import {
	BASEURL
} from './const.js'

/**
 * 封装 uni.request
 * @param {string} url 接口路径
 * @param {object} data 请求参数
 * @param {string} method 请求方法 GET/POST
 * @param {boolean} isShowLoading 是否显示 loading，默认 true
 * @returns {Promise}
 */
function request(url, method = 'GET', data = {}, isShowLoading = true) {
	const token = uni.getStorageSync('token');
	const header = {
		'content-type': 'application/json',
		...(token ? {
			Authorization: 'Bearer ' + token
		} : {}),
	};

	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL + url,
			data,
			method,
			header,
			success(res) {
				if (res.data.code == 200) {
					resolve(res.data);
				} else if (res.data.code == 401) {
					methods.login().then(resLogin => {
						request(url, data, method, isShowLoading).then(result => {
							resolve(result)
						})
					})
				} else {
					resolve(res.data);
				}
			},
			fail(err) {
				uni.showToast({
					title: '网络异常',
					icon: 'none'
				});
				reject(err);
			},
			complete() {},
		});
	});
}
export default request